<?php

namespace app\backend\model;

use app\backend\model\enum\Status;
use app\backend\services\auth\UserInterface;

class Admin extends Base implements UserInterface
{

    const ADMIN = 1;

    public static $statusLabels
        = [
            Status::STATUS_DISABLE => '禁止',
            Status::STATUS_NORMAL  => '正常',
        ];

    public static $labels
        = [
            'id'               => 'ID',
            'username'         => '用户名',
            'password'         => '密码',
            'nickname'         => '昵称',
            'confirm_password' => '确认密码',
            'status'           => '状态',
            'roles'            => '角色',
            'create_time'      => '创建时间',
            'update_time'      => '更新时间',
            'avatar'           => '头像',
        ];

    protected $hidden = ['password'];

    public static function onBeforeDelete($model)
    {
        if (1 == $model->id)
        {
            return false;
        }
        AuthGroupAccess::destroy(
            function ($query) use ($model)
            {
                $query->where(['uid' => $model->id]);
            }
        );
    }

    protected function getStatusAttr($val)
    {
        return $val == 1;
    }

    protected function setStatusAttr($val)
    {
        return $val ? 1 : 0;
    }

    protected function getLastLoginTimeAttr($time)
    {
        return $time > 0 ? date("Y-m-d H:i:s", $time) : $time;
    }

    protected function setLastLoginTimeAttr($time)
    {
        return strpos($time, '-') === false ? $time : strtotime($time);
    }

    protected function setCreateTimeAttr($time)
    {
        return strpos($time, '-') === false ? $time : strtotime($time);
    }

    protected function setUpdateTimeAttr($time)
    {
        return strpos($time, '-') === false ? $time : strtotime($time);
    }

    protected function setPasswordAttr($password)
    {
        return hashPassword($password);
    }

    public function roles()
    {
        return $this->role()->select();
    }

    public function role()
    {
        return $this->belongsToMany(Role::class, RolePermission::class, 'role_id', 'admin_id');
    }

    public function authority(): bool
    {
        return (int)$this->status === Status::STATUS_NORMAL;
    }


}
